$(function () {
    var queryUrl = '../scarplist/list';
    var Id = getQueryString('Id');
    if(Id){
        queryUrl += '?Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: '备件名称', name: 'name', index: 'NAME', width: 60},
            {label: '备件规格', name: 'specs', index: 'SPECS', width: 90},
            {label: '报废数量', name: 'scarpNum', index: 'SCARP_NUM', width: 45},
            {label: '设备组织', name: 'devOrgName', index: 'SUB_EQUIP'},
            {label: '所属设备', name: 'subEquipName', index: 'SUB_EQUIP', width: 80},
            {label: '备注', name: 'remark', index: 'REMARK', width: 80},
            {
                label: '创建时间', name: 'createTime', index: 'CREATE_TIME', width: 85, formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd hh:mm");
                }
            },
            {
                label: '当前状态', name: 'statusStr', index: 'STATUS', width: 60,
                formatter: function (value, col, row) {
                    return sysEnums.SPARE_PART_SCARP_STATUS[row.status];
                }
            },
            {
                label: '处理进度', name: 'devCode', width: 45, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>详情</button>";
                }
            },
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: 'status', name: 'status', index: 'status', hidden: true},

        ],
    });
});


let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        scarpList: {
            subEquip: '',
            updateTime: '',
            updateUser: '',
            createTime: '',
            createUser: '',
            delFlag: '',
            workshopLeader: '',
            gcsbjs: '',
            equipTech: '',
            repairLeader: '',
            remark: '',
            suggest: '',
            descript: '',
            scarpNum: '',
            line: '',
            proceNo: '',
            specs: '', // 备件规格
            useUnit: '', // 备件使用单位
            spareId: '',// 备件ID
            name: '11', // 备件名称
            id: '',
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'change'}
            ]
        },
        q: {
            partName: '', // 备件名称
            spec: '', // 备件规格
            producor: '', // 供应厂家
            status: '',
            partCode:'',
            erpCode:'',
            createUserName:''
        },
        number:0,//记录数
        scarpName:'',//记录名
        scarp: {
            idList: [],
            state: 0,
            checkRemark: ""
        },
        statusList: enumsToList('SPARE_PART_SCARP_STATUS'),
        auditTableColumns: [
            {
                title: '环节名称',
                key: 'workitemName',
                width: 190
            },
            {
                title: '审批状态',
                key: 'state',
                width: 100,
                render: (h, params) => {
                    return sysEnums.OA_CHECK_FLAG_SCARP[params.row.state];
                }
            },
            {
                title: '审批人',
                key: 'approverName',
                width: 100
            },
            {
                title: '审批时间',
                key: 'approveDate',
                width: 160
            },
            {
                title: '审批备注',
                key: 'remark',
                width: 150
            }
        ],
        auditTableData: [], // 审批table数据


    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.scarpList = {
                subEquip: '',
                updateTime: '',
                updateUser: '',
                createTime: '',
                createUser: '',
                delFlag: '',
                workshopLeader: '',
                gcsbjs: '',
                equipTech: '',
                repairLeader: '',
                remark: '',
                suggest: '',
                descript: '',
                scarpNum: '',
                line: '',
                proceNo: '',
                specs: '', // 备件规格
                useUnit: '', // 备件使用单位
                spareId: '',// 备件ID
                name: '', // 备件名称
                id: '',
            };
        },
        update: function (event) {
            var data = getSelectedRowData("#jqGrid");
            if (data.id == null) {
                return;
            }
            if (data.status == 1) {
                alert("已审核完的记录不允许修改！", function () {
                    vm.reload();
                });
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(data.id);
        },
        saveOrUpdate: function (event) {
            let url = vm.scarpList.id == (null || '') ? "../scarplist/save" : "../scarplist/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.scarpList),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../scarplist/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../scarplist/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.scarpList = r.scarpList;
                }
            });
        },
        //显示备件列表-物料编码
        getSparePart: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件',
                content: './sparePartQuery.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.scarpList.name = res.name;
                        vm.scarpList.useUnit = res.useUnit;
                        vm.scarpList.specs = res.spec;
                        vm.scarpList.spareId = res.id;
                        layer.close(index);
                    }
                }
            })
        },
        //显示设备列表
        getDeviceInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择设备',
                content: './scarpdev.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getDeviceInfo();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.scarpList.line = res.devProductName;//生产线名称
                        vm.scarpList.proceNo = res.devProceName//工序号名称
                        vm.scarpList.subEquip = res.devName;//设备名称
                        layer.close(index);
                    }
                }
            })
        },
        // 审核
        approval: function () {
            var data = getSelectedRowDatas("#jqGrid");
            var idList = getSelectedRows("#jqGrid");
            console.log(data)
            let count = 0
            let names = data.map(item => [item.name, item.specs, item.scarpNum].join(",")).join(",");
            // 判断
            for (var i = 0; i < data.length; i++) {
                count += parseInt(data[i].scarpNum);
                if (data[i].status !== '2') {
                    alert("只能审核处于[车间审核]状态的报废记录！", function () {
                        vm.reload();
                    });
                    return false;
                }
            }

            // 清空初始化
            vm.number = count
            vm.scarpName = names
            vm.scarp.idList = idList;
            vm.scarp.state = 1;
            vm.scarp.checkRemark = '';
            openWindow({
                title: "车间审核",
                area: ['500px', '300px'],
                content: jQuery("#appv"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: "../scarplist/checkSpScarp",
                        params: JSON.stringify(vm.scarp),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                // 清空初始化
                                vm.scarp.id = '';
                                vm.scarp.checkRemark = '';
                                vm.reload();
                            });
                        }
                    })
                    layer.close(index);
                }
            });
        },
        PEapproval: function () {
            var data = getSelectedRowDatas("#jqGrid");
            var idList = getSelectedRows("#jqGrid");
            let count = 0
            let names = data.map(item => [item.name, item.specs, item.scarpNum].join(",")).join(",");
            // 判断
            for (var i = 0; i < data.length; i++) {
                count += parseInt(data[i].scarpNum);
                if (data[i].status !== '3') {
                    alert("只能审核处于[PE审核]状态的报废记录！", function () {
                        vm.reload();
                    });
                    return false;
                }
            }

            // 清空初始化
            vm.number = count
            vm.scarpName = names
            vm.scarp.state = 1;
            vm.scarp.checkRemark = '';
            vm.scarp.idList = idList;
            openWindow({
                title: "PE审核",
                area: ['500px', '300px'],
                content: jQuery("#appv"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: "../scarplist/checkSpScarp",
                        params: JSON.stringify(vm.scarp),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                // 清空初始化
                                vm.scarp.id = '';
                                vm.scarp.checkRemark = '';
                                vm.reload();
                            });
                        }
                    })
                    layer.close(index);
                }
            });

        },
        //审核详情
        shviewOption: function (res) {
            let data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysoaprocess/queryAll',
                params: {busId: data.id, busType: 'SCARP_REPAIR'},
                type: 'POST',
                successCallback: function (res) {
                    vm.auditTableData = res.list;
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['700px', '480px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: $('#auditHistoryArea')
                    });
                }
            });
        },
        reload: function (event) {
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: vm.q,
                page: page
            }).trigger("reloadGrid",[{page: 1}]);
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                partName: '', // 备件名称
                spec: '', // 备件规格
                producor: '', // 供应厂家
                status: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (!res.err) {
                this.$Loading.finish();
                alert('导入成功', function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        exportData: function () {
            exportFile('#rrapp', '../scarplist/import', {'name': vm.q.name});
        }
    }
});
